package cn.tedu.wms.product.service.impl;

import cn.tedu.wms.product.ex.ServiceException;
import cn.tedu.wms.product.mapper.StockMapper;
import cn.tedu.wms.product.pojo.dto.StockDTO;
import cn.tedu.wms.product.pojo.entity.Stock;
import cn.tedu.wms.product.pojo.vo.StockListVO;
import cn.tedu.wms.product.pojo.vo.StockStandardVO;
import cn.tedu.wms.product.service.StockService;
import cn.tedu.wms.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 处理库存数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Service
@Slf4j
public class StockServiceImpl implements StockService {

    @Autowired
    StockMapper stockMapper;

    public StockServiceImpl() {
        System.out.println("创建业务实现类对象：StockServiceImpl");
    }

    @Override
    public void addNew(StockDTO stockDTO) {
       log.debug("开始处理添加库存的业务,参数: {}",stockDTO);
       Long productId=stockDTO.getProductId();
       int rows=stockMapper.countByProductId(productId);
       if(rows>=1){
           String message="添加库存失败,产品id已存在";
           throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
       }
        Stock stock=new Stock();
        BeanUtils.copyProperties(stockDTO,stock);

        log.debug("即将插入库存数据,参数: {}",stock);
        int row=stockMapper.insert(stock);
        if(row!=1){
            String message="添加库存失败,服务器忙,请稍候重试";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理删除库存业务,参数 :{}",id);
        StockStandardVO standardById = stockMapper.getStandardById(id);
        if(standardById==null){
            String message="删除库存失败,该库存数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        log.debug("即将根据id删除库存数据,参数:{}",id);
        int rows = stockMapper.deleteById(id);
        if(rows!=1){
            String message="删除库存失败,服务器忙,请稍候重试";
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }

    }

    @Override
    public StockStandardVO getStandard(Long id) {
        log.debug("开始处理查询[库存详情]");
        StockStandardVO standardById = stockMapper.getStandardById(id);
        return standardById;
    }

    @Override
    public List<StockListVO> list() {
        log.debug("开始处理[库存列表]");
        List<StockListVO> list = stockMapper.list();
        return list;
    }
}
